package com.heima.search.service;

import com.heima.common.threadlocal.UserThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class SearchHistoryService {

    public static final String KEY_PREFIX = "leadnews:search:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Async("taskExecutor")
    public void saveSearchHistory(String keyword, Integer userId, String equipId){
        // 存入redis的zset，score就是查询次数
        redisTemplate.boundZSetOps(buildKey(userId, equipId)).incrementScore(keyword, 1);

        // TODO 只保留10条历史记录
        Long size = redisTemplate.boundZSetOps(buildKey(userId, equipId)).size();
        if(size > 10){
            // 获取rank最小的
            List<String> oldDataList = new ArrayList<>(redisTemplate.boundZSetOps(buildKey(userId, equipId)).range(0, 0));
            redisTemplate.boundZSetOps(buildKey(userId, equipId)).remove(oldDataList.get(0));
        }

    }


    private String buildKey(Integer userId, String equipId){
        if(userId == null || userId <= 0){
            return KEY_PREFIX + equipId;
        }else{
            return KEY_PREFIX +userId;
        }
    }

    public List<String> loadHistory(String equipmentId, Integer pageSize, String minRankData) {
        Integer userId = UserThreadLocalUtils.getUserId();
//        Set<String> list = redisTemplate.boundZSetOps(buildKey(userId, equipmentId)).reverseRangeByScore(0, Double.MAX_VALUE);
//        if(CollectionUtils.isEmpty(list)){
//            return new ArrayList<>(0);
//        }
//        return new ArrayList<>(list);
        // TODO 真的要分页，如何来实现？
        Long startIndex = 0L;
        if(StringUtils.isEmpty(minRankData)){
            // 第一页
            startIndex = 0L;
        }else{
            // 非第一页，根据最小数据获取排名
            Long rank = redisTemplate.boundZSetOps(buildKey(userId, equipmentId)).reverseRank(minRankData);
            startIndex = rank + 1;
        }
        // 根据排名获取下一页数据
        Set<String> list = redisTemplate.boundZSetOps(buildKey(userId, equipmentId)).reverseRange(startIndex, startIndex+pageSize-1);
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>(0);
        }
        return new ArrayList<>(list);
    }
}